package com.xxl.job.executor.common.util;

//import org.apache.logging.log4j.LogManager;
//import org.apache.logging.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class FileUtil {

//	private static Logger logger = LogManager.getLogger(FileUtil.class);
	
	/**
	 * 写文件到共享存储
	 * @param body
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static File writeFile(byte[] body, String filePath) throws IOException {
		File file = new File(filePath);
		if (!file.getParentFile().exists()) {
            //logger.info(filePath + "文件夹不存在，新建文件夹");
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
			file.createNewFile();
        }
        FileOutputStream fop = null;
        try {
            fop = new FileOutputStream(file, true);
            fop.write(body);
            fop.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fop != null) {
				fop.close();
            }
        }
        return file;

    }
	
	/**
	 * 功能描述：将消息内容生成文件才能够对部中心发出请求
	 * @return
	 */
	public static File writeFile(byte[] body, String filePath, String fileName) throws IOException {
		File file = new File(filePath + File.separator + fileName + ".json");
		if (!file.getParentFile().exists()) {
			//logger.info(filePath + "文件夹不存在，新建文件夹");
			file.getParentFile().mkdirs();
		}
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream fop = null;
		try {
			fop = new FileOutputStream(file, true);
			fop.write(body);
			fop.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}finally {
			if (fop != null) {
				fop.close();
			}
		}
		return file;

	}


	public static void writeZip(List<File> files ,String zipFilePath) {
		FileInputStream nFileInputStream = null;
		ZipOutputStream nZipOutputStream = null;
		try {
			nZipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
			for (File file : files) {
				nFileInputStream = new FileInputStream(file);
				nZipOutputStream.putNextEntry(new ZipEntry(file.getName()));
				int len;
				while ((len = nFileInputStream.read()) != -1) {
					nZipOutputStream.write(len);
					nZipOutputStream.flush();
				}
				nFileInputStream.close();
			}
			nZipOutputStream.close();
			//logger.info("生成ZIP文件成功！");
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void writeZip(File file ,String zipFilePath) {
		List<File> fileList = new ArrayList<File>();
		fileList.add(file);
		writeZip(fileList,zipFilePath);
	}
	
	
	/**
	 * 新建文件(.zip)
	 * @param datas Map数组，key是文件名，byte[]是数据
	 * @param output	输出流
	 * @param charset	编码
	 */
	public static void zipStringToOutputStream(Map<String, byte[]> datas,
		OutputStream output, String charset) {
		ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(output));
		Set<Entry<String, byte[]>> dataEntrys = datas.entrySet();
		for (Entry<String, byte[]> data : dataEntrys) {
			try {
				InputStream bufferIn = new BufferedInputStream(new ByteArrayInputStream(data.getValue()));
				byte[] bs = new byte[1024];
				Arrays.fill(bs, (byte) 0);
				zipout.setEncoding(charset);
				zipout.putNextEntry(new ZipEntry(data.getKey()));//创建压缩文件内的文件
				int len = -1;
				while ((len = bufferIn.read(bs)) > 0) {//写入文件内容
					zipout.write(bs, 0, len);
				}
				bufferIn.close();
			} catch (Exception e) {
//				logger.error("字符串ZIP流写入压缩文件【" + data.getKey() + "】失败：" + e.getMessage());
			}
		}
		try {
			zipout.close();
		} catch (IOException e) {
//			logger.error("ZIP流关闭异常：" + e.getMessage());
		}
	}
	
	/**
	 * 写内容到分布式文件系统，返回路径
	 * @param body
	 * @return
	 * @throws IOException
	 */
	public static String writeFile(byte[] body) throws IOException {
		return "";
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		FileOutputStream fout = new FileOutputStream("F:/aaa.zip");
		Map<String, byte[]> datas = new HashMap<String, byte[]>();
		datas.put("111.json", "测试来来来".getBytes());
		datas.put("222.json", "bbbbb".getBytes());
		datas.put("333.json", "ccccc".getBytes());
		zipStringToOutputStream(datas , fout , "UTF-8");
	}
}
